import 'package:dio/dio.dart';
import 'package:fluwx/fluwx.dart';
import 'package:village_android/component/icon_tile.dart';
import 'package:village_android/component/jd_button.dart';
import 'package:village_android/model/order_model.dart';
import 'package:village_android/model/wx_pay_model.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';

import 'dart:convert';
import 'dart:io' as H;

import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class PayPage extends StatefulWidget {
  OrderModel orderModel;

  PayPage({this.orderModel});

  @override
  _PayPageState createState() => _PayPageState();
}

class _PayPageState extends State<PayPage> {
  var _result;
  var payState;
  WXPayInfoModel wxPayInfo;

  @override
  void initState() {
    super.initState();
    toListen(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('付款详情'),
      ),
      body: localWidget(),
      bottomNavigationBar: initBottom(),
    );
  }

  Widget localWidget() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(20.0),
      child: Column(children: <Widget>[
        IconTile(leading: Icons.payment, title: "微信支付", action: () {}),
        Divider(height: 2.0, color: Colors.black38),
        initTitle(),
        initOrderId(),
        initType(),
        initUserName(),
        initRemark(),
      ]),
    );
  }

  TextFormField initUserName() {
    return TextFormField(
      enabled: false,
      initialValue: widget.orderModel.name,
      decoration: InputDecoration(labelText: '姓名'),
    );
  }

  TextFormField initOrderId() {
    return TextFormField(
      enabled: false,
      initialValue: widget.orderModel.orderId,
      decoration: InputDecoration(labelText: '订单ID'),
    );
  }

  TextFormField initTitle() {
    return TextFormField(
      enabled: false,
      initialValue: widget.orderModel.title,
      decoration: InputDecoration(labelText: '标题'),
    );
  }

  TextFormField initAmount() {
    return TextFormField(
      enabled: false,
      initialValue: widget.orderModel.amount,
      decoration: InputDecoration(labelText: '金额'),
    );
  }

  TextFormField initRemark() {
    return TextFormField(
      enabled: false,
      initialValue: widget.orderModel.remark,
      decoration: InputDecoration(labelText: '备注'),
    );
  }

  TextFormField initType() {
    return TextFormField(
      enabled: false,
      initialValue: "卫生费",
      decoration: InputDecoration(labelText: '类型'),
    );
  }

  Widget initBottom() {
    return BottomAppBar(
        child: Row(
      children: <Widget>[
        Expanded(
            child: JdButton(
          callBack: () {
            toWeChatPay();
//            toDemoWeChatPay();
          },
          text: "合计: " + widget.orderModel.amount + "元" + "(微信付款)",
          color: Colors.green,
        )),
      ],
    ));
  }


  void toWeChatPay() {
    FormData formData = new FormData.from(widget.orderModel.toJson());
    HttpUtils.postForm("/api/order/create",
        formData: formData, context: context, success: (data) {
      wxPayInfo = WXPayInfoModel.fromJson(data);

      var payRes = fluwx.payWithWeChat(
          appId: wxPayInfo.appid,
          partnerId: wxPayInfo.partnerid,
          prepayId: wxPayInfo.prepayId,
          packageValue: wxPayInfo.package,
          nonceStr: wxPayInfo.noncestr,
          timeStamp: int.parse(wxPayInfo.timestamp),
          sign: wxPayInfo.sign,
          signType: '',
          extData: '');
      print(payRes);
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }

  void toListen(BuildContext context) {

    fluwx.responseFromPayment.listen((data) {
      _result = "${data.errCode}";
      print('_result_result  > $_result       errStrerrStr  ${data.errStr}');
      if (_result == '-2') {
        payState = false;
        CommonUtils.showToast(context, '用户取消');
      } else if (_result == '0') {
        payState = true;
        CommonUtils.showToast(context, '付款成功');

        //更新申请单
        //跳出页面
        Navigator.of(context).pop(wxPayInfo.orderId);

      } else {
        payState = false;
      }

      if (!mounted) return;
      setState(() {});
    });
  }
}
